package com.jiegui.payinterface.utils;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.jiegui.common.core.redis.RedisCache;
import com.jiegui.common.model.AccessToken;
import com.jiegui.common.utils.spring.SpringUtils;
import com.jiegui.payinterface.bean.wxapplet.BaseRes;
import com.jiegui.payinterface.bean.wxapplet.send.SubscribeMsg;
import com.jiegui.payinterface.bean.wxapplet.urlscheme.UrlScheme;
import com.jiegui.payinterface.bean.wxapplet.urlscheme.UrlSchemeRes;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

/**
 * 微信小程序工具
 *
 * @author wuqicheng
 * @date 2021/3/19
 */
@Slf4j
public class WxAppletUtils {

    /**
     * 获取access_token的接口地址（GET） 限200（次/天）
     */
    private final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取小程序scheme码
     */
    private final static String GENERATE_SCHEME_URL = "https://api.weixin.qq.com/wxa/generatescheme?access_token=ACCESS_TOKEN";

    /**
     * 订阅消息推送
     */
    private final static String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";

    /**
     * 检测响应是否成功
     */
    private static void checkRes(BaseRes res) throws Exception {
        if (res.getErrcode() != 0) {
            throw new Exception(res.getErrmsg());
        }
    }

    /**
     * 获取小程序access_token
     */
    public static String getAccessToken(String appid, String secret) throws Exception {
        RedisCache redisCache= SpringUtils.getBean(RedisCache.class);
        String url = ACCESS_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", secret);
        String cacheKey = "applet:" + appid;
        // 从缓存获取
        AccessToken cacheAccessToken = JSONObject.toJavaObject( redisCache.getCacheObject(cacheKey),AccessToken.class);
        if (cacheAccessToken != null) {
            return cacheAccessToken.getAccess_token();
        }

        String result = HttpUtil.request(url, "GET");
        log.info("getAccessToken 小程序=[{}] accessToken=[{}]", appid, result);
        AccessToken accessToken = JSON.parseObject(result, AccessToken.class);
      //  checkRes(accessToken);
        // 存入缓存
        redisCache.setCacheObject(cacheKey,accessToken,accessToken.getExpires_in(), TimeUnit.SECONDS);
        //RedisUtil.setExJson(cacheKey, accessToken, accessToken.getExpires_in());
        return accessToken.getAccess_token();
    }

    /**
     * 获取小程序scheme码
     * 适用于短信、邮件、外部网页等拉起小程序的业务场景
     */
    public static String createUrlScheme(String appid, String secret, UrlScheme urlScheme) throws Exception {
        String url = GENERATE_SCHEME_URL.replace("ACCESS_TOKEN", getAccessToken(appid, secret));

        String result = HttpUtil.requestJson(url, JSON.toJSONString(urlScheme), "POST");
        log.info("createUrlScheme urlScheme=[{}] result=[{}]", urlScheme, result);
        UrlSchemeRes urlSchemeRes = JSON.parseObject(result, UrlSchemeRes.class);
        //checkRes(urlSchemeRes);
        return urlSchemeRes.getOpenlink();
    }

    /**
     * 订阅消息推送
     */
    public static BaseRes sendMessage(String appid, String secret, SubscribeMsg subscribeMsg) throws Exception {
        String url = SEND_URL.replace("ACCESS_TOKEN", getAccessToken(appid, secret));

        String result = HttpUtil.requestJson(url, JSON.toJSONString(subscribeMsg), "POST");
        log.info("sendMessage subscribeMsg=[{}] result=[{}]", subscribeMsg, result);
        BaseRes res =  JSON.parseObject(result, (Type) UrlSchemeRes.class);
        checkRes(res);
        return res;
    }

}

